package cn.jietuo.first.class03;

import java.util.Arrays;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/6/21
 * @description:
 */
public class Code04_Partition2 {

    /**
     * arr[L ..R] 中玩荷兰国旗问题,以arr[R]做划分值
     * <p>
     * <arr[R] 放左边  ==arr[R] 放中间  >arr[R] 放右边
     *
     * @param arr
     * @param l
     * @param r
     * @return
     */
    public static int[] netherLandsFlag(int[] arr, int l, int r) {
        if (l > r) {
            return new int[]{-1, -1};
        }
        if (l == r) {
            return new int[]{l, r};
        }
        int lessIndex = l - 1;
        int curIndex = l;
        int largeIndex = r + 1;
        int num = arr[r];
        while (curIndex < largeIndex) {
            if (arr[curIndex] > num) {
                swap(arr, curIndex, --largeIndex);
            } else if (arr[curIndex] == num) {
                curIndex++;
            } else {
                swap(arr, ++lessIndex, curIndex++);
            }
        }
        return new int[]{lessIndex + 1, largeIndex - 1};
    }

    private static void swap(int[] arr, int curIndex, int i) {
        int temp = arr[curIndex];
        arr[curIndex] = arr[i];
        arr[i] = temp;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{2, 4, 6, 3, 4, 1, 3, 2, 3};
        printArr(arr);
        int[] ints = netherLandsFlag(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(ints));
        System.out.println("--------");
        printArr(arr);
    }

    private static void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
